<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    const arr = [
      {
        name: '张三',
        id: 1,
        pid: ''
      },
      {
        name: '李四',
        id: 2,
        pid: ''
      },
      {
        name: '张三三',
        id: 3,
        pid: 1
      },
      {
        name: '张三三三',
        id: 4,
        pid: 3
      },
      {
        name: '李四四',
        id: 5,
        pid: 2
      },
    ]

    // 递归函数
    function transListToTree(arr, pid) {
      const newArr = []
      arr.forEach(item => {
        if (item.pid === pid) {
          // 调用transListToTree 找子集
          const children = transListToTree(arr, item.id)
          // 是否有子集
          if(children.length) {
            item.children = children
          }
          newArr.push(item)
        }
      })
      return newArr
    }

    console.log(transListToTree(arr, ''))
  </script>
</body>
</html>